package com.imau.servlet;

import com.imau.bean.User;
import com.imau.mapper.UserMapper;
import com.imau.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    private SqlSession sqlSession;
    private UserMapper userMapper;

    @Override
    public void init() throws ServletException {
        sqlSession = SqlSessionUtil.getSqlSession();
        userMapper  =sqlSession.getMapper(UserMapper.class);
    }

    @Override
    public void destroy() {

        sqlSession.close();

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //判断用户名是否存在
        if(userMapper.selectByUserName(username)!=null)
        {
            resp.getWriter().write("用户名已存在!!");
        }else if("".equals(username) || "".equals(password))
        {
            resp.getWriter().write("用户名密码不能为空!!");
        }else {

            int i = userMapper.insertUser(new User(null, username, password));

            if(i > 0 )
            {

                resp.sendRedirect(req.getContextPath()+"/login.html");
            }
        }




    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
